package main

import (
	"context"
	"fmt"
	"log"
	"net"
	service "server/gen/go/pet/v1"
	"strconv"
	"time"

	"google.golang.org/genproto/googleapis/type/datetime"
	"google.golang.org/grpc"
)

var i int = 0

type server struct {
	service.UnimplementedPetStoreServiceServer
	id2pet map[string]*service.Pet
}

func (s *server) GetPet(ctx context.Context, in *service.GetPetRequest, opts ...grpc.CallOption) (*service.GetPetResponse, error) {
	res, bol := s.id2pet[in.GetPetId()]

	if bol {
		return &service.GetPetResponse{Pet: res}, nil
	} else {
		fmt.Println("没有找到")
		return nil, nil
	}
}
func (s *server) PutPet(ctx context.Context, in *service.PutPetRequest, opts ...grpc.CallOption) (*service.PutPetResponse, error) {
	creat_time := datetime.DateTime{
		Year:    int32(time.Now().Year()),
		Month:   int32(time.Now().Month()),
		Day:     int32(time.Now().Day()),
		Hours:   int32(time.Now().Hour()),
		Minutes: int32(time.Now().Minute()),
		Seconds: int32(time.Now().Second()),
		Nanos:   int32(time.Now().Nanosecond()),
	}
	res := service.Pet{
		PetType:   in.GetPetType(),
		PetId:     strconv.Itoa(i),
		Name:      in.GetName(),
		CreatedAt: &creat_time,
	}
	s.id2pet[strconv.Itoa(i)] = &res
	i++
	return &service.PutPetResponse{Pet: &res}, nil
}

func (s *server) DeletePet(ctx context.Context, in *service.DeletePetRequest, opts ...grpc.CallOption) (*service.DeletePetResponse, error) {
	_, bol := s.id2pet[in.GetPetId()]
	if bol {
		delete(s.id2pet, in.GetPetId())
		return &service.DeletePetResponse{}, nil
	} else {
		fmt.Println("没有找到")
		return nil, nil
	}
}
func (s *server) mustEmbedUnimplementedPetStoreServiceServer() {}
func main() {
	s := grpc.NewServer()
	service.RegisterPetStoreServiceServer(s, &server{id2pet: make(map[string]*service.Pet)})
	port := ":8080"
	listener, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatal("服务启端动失败", err)
	}
	log.Print("服务端启动成功" + port)
	_ = s.Serve(listener)
}
